﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using TSVNAddin.SVN;

namespace TSVNAddin.Core
{
	public class PathRenamedAction
	{
		private readonly IVersionControl _VersionControl;
		private readonly IFileStorage _FileStorage;

		public PathRenamedAction(IVersionControl versionControl, IFileStorage fileStorage)
		{
			_VersionControl = versionControl;
			_FileStorage = fileStorage;
		}

		public virtual void Execute(string toPath, string oldName)
		{
			string sourcePath = GetSourcePath(toPath, oldName);

			if (sourcePath == toPath)
				return;

			_FileStorage.Move(toPath, sourcePath);

			try
			{
				_VersionControl.Move(sourcePath, toPath);
			}
			catch
			{
				_FileStorage.Move(sourcePath, toPath);
				throw;
			}
		}

		private static string GetSourcePath(string toPath, string oldName)
		{
			if (toPath.EndsWith("\\"))
				return GetDirectorySourcePath(toPath, oldName);

			if (!Path.HasExtension(oldName))
				oldName += Path.GetExtension(toPath);

			string directory = Path.GetDirectoryName(toPath);
			return Path.Combine(directory, oldName);
		}

		private static string GetDirectorySourcePath(string toPath, string oldName)
		{
			string directory = toPath.Remove(toPath.LastIndexOf("\\"));
			string directory2 = directory.Remove(directory.LastIndexOf("\\"));
			return Path.Combine(directory2, oldName) + "\\";
		}
	}
}
